Prepared Statement
A prepared statement object is like a regular statement object in that it can be used to execute sql statement. The difference is that the sql in a prepared statement is the precompiled by the database for faster execution. Once a prepared statement has been compiled it can still be customized by existing predefined parameters use ? Character as a place holder where values to be substitute later.
Methods for prepared statement.
clearParameters()
setInt(column number,value)
setDouble(column number,value)
setString(column number,value)
Program on Prepared Statement
import java.sql.*;
public class Insert
{
public static void main(String args[])
{
Connection con=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:vision","scott","tiger");
PreparedStatement st=con.prePareStatement
(“insert into abc values(?,?,?)”);
String mna;
int meno,msal;
Scanner read=new Scanner(System.in);
int ch='y';
while((char)ch!='n')
{
System.out.println("Enter Empno,name,Salary");
meno=read.nextInt();
mna=read.nextLine();
msal=read.nextInt();
st.setInt(1,meno);
st.setString(2,mna);
st.setInt(3,msal);
st.executeUpdate();
System.out.println("Continue Y/n");
ch=read.nextInt();
}
st.close();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
if(con!=null)
con.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
}
Write a program on Joins
import java.sql.*;
public class Insert
{
public static void main(String args[])
{
Connection con=null;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:vision","scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(“select abc.eno,abc.na,abc.sal from
abc,abc1 where abc.eno=abc1.eno” );
while(rs.next())
{
System.out.println(rs.getInt(1)+” “+rs.getString(2)+” “+
rs.getInt(3));
}
rs.close();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
if(con!=null)
con.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
}